#include "mygradetablewidget.h"
#include "qprocess.h"
#include "qscreen.h"

#include <QTableWidget>
#include<QTableWidgetItem>
#include<QGroupBox>
#include<QDebug>
#include<QSpacerItem>
#include<QDateTime>
#include<QThread>

#include<QDateEdit>
#include<QPushButton>
#include<QHBoxLayout>
#include<QVBoxLayout>
#include<QTime>
#include<QMessageBox>
#include<QLineEdit>
#include<QLabel>
#include <windows.h>
#include<QApplication>
#include<QStringList>
#include<QHeaderView>
#include<QDir>
#include <algorithm>
#include "Python.h"

#define MYLOG qDebug() << "[" << __FILE__ << ":" << __LINE__ << ":" << QThread::currentThread() << __func__ << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz")<< "]"
MyGradeTableWidget::MyGradeTableWidget(QWidget *parent) :
  QWidget(parent,Qt::WindowStaysOnTopHint)
{
    qRegisterMetaType<QVector<Target_Info_Table>>("QVector<Target_Info_Table>&");
    //获取屏幕属性
    QScreen *screen = QGuiApplication::primaryScreen();

    qreal lcd_width = screen->size().width();
    qreal lcd_height = screen->size().height();

  this->resize(lcd_width - 300,lcd_height - 300);

  move(150,150);

  create();
  searchName = {};

  QDate m_date = QDate::currentDate();
  currentDate = m_date.toString("yyyy-MM-dd");

  connect(btnCheck,SIGNAL(clicked()),this,SLOT(check_clicked()));
  connect(btnOut,SIGNAL(clicked()),this,SLOT(out_clicked()));
  connect(dateEdit,SIGNAL(dateChanged(QDate)),this,SLOT(dateChange(QDate)));
  //传递要查找的靶号和分组
  connect(this,SIGNAL(signal_addr_groupnumber_change(int,int)),this,SLOT(changeAddrandGroupnumber(int,int)));
  //传递要查找的日期
  connect(this,SIGNAL(signalDateChange(QString)),this,SLOT(changeDate(QString)));


  emit signalDateChange(currentDate);

}

MyGradeTableWidget::~MyGradeTableWidget()
{
  delete baWei;
  baWei = nullptr;

  delete fenZuIndex;
  fenZuIndex = nullptr;
  delete name;
  name = nullptr;
  delete onlyHuanShu;
  onlyHuanShu = nullptr;
  delete allSum;
  allSum = nullptr;
  delete tableWidget;
  tableWidget = nullptr;
  delete lineEditGroup;
  lineEditGroup = nullptr;
  delete lineEditNum;
  lineEditNum = nullptr;
  delete btnCheck;
  btnCheck = nullptr;
  delete btnOut;
  btnOut = nullptr;
  delete dateEdit;
  dateEdit = nullptr;
  sqliteTools->closeDataBase();
  delete sqliteTools;
  sqliteTools = nullptr;

}


void MyGradeTableWidget::create()
{
  setWindowTitle("成绩导出");
  //弹簧
  QSpacerItem *h_spacer = new QSpacerItem(10,10,QSizePolicy::Expanding,QSizePolicy::Minimum);
  //  QSpacerItem *v_spacer = new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Expanding);


  QGroupBox *groupBox = new QGroupBox(this);
  groupBox->setTitle("筛选");

  QLabel *labelGroup = new QLabel("分组:",this);
  QLabel *labelNum = new QLabel("靶号:",this);
  QLabel *labelTime = new QLabel("时间:",this);

  lineEditGroup = new QLineEdit(this);

  lineEditNum = new QLineEdit(this);

  dateEdit = new QDateEdit(this);

  dateEdit->setDate(QDate::currentDate());

  btnCheck = new QPushButton("查找",this);

  QHBoxLayout *h_layout_1 = new QHBoxLayout;

  h_layout_1->addItem(h_spacer);
  h_layout_1->addWidget(labelGroup);
  h_layout_1->addWidget(lineEditGroup);

  h_layout_1->addWidget(labelNum);
  h_layout_1->addWidget(lineEditNum);
  h_layout_1->addItem(h_spacer);
  h_layout_1->addWidget(labelTime);
  h_layout_1->addWidget(dateEdit);
  h_layout_1->addWidget(btnCheck);
  h_layout_1->addItem(h_spacer);

  groupBox->setLayout(h_layout_1);

  tableWidget = new QTableWidget(this);
  tableWidget->verticalHeader()->setHidden(true);
  tableWidget->setRowCount(BulletNumber);
  tableWidget->setColumnCount(34);
  tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{font:19pt '宋体';};");
  QStringList strList;
  strList<<tr("靶号")<<tr("分组")<<tr("姓名");
//  xlsx.write(1,1,"靶号");
//  xlsx.write(1,2,"分组");
//  xlsx.write(1,3,"姓名");
  for(int i = 1;i < 31;i++)
    {
      strList.append(QString::asprintf("%d",i));
    }
  strList<<tr("总环数");
  tableWidget->setHorizontalHeaderLabels(strList);

  QHBoxLayout *h_layout_2 = new QHBoxLayout;

  btnOut = new QPushButton("导出",this);

  h_layout_2->addItem(h_spacer);
  h_layout_2->addWidget(btnOut);
  h_layout_2->addItem(h_spacer);

  QVBoxLayout *v_layout_1 = new QVBoxLayout;

  v_layout_1->addLayout(h_layout_2);

  QVBoxLayout *v_layout_2 = new QVBoxLayout(this);

  v_layout_2->addWidget(groupBox);
  v_layout_2->addWidget(tableWidget);
  v_layout_2->addLayout(v_layout_1);

  setStyleSheet("QLabel,QPushButton,QLineEdit,QGroupBox,QDateEdit,QTableWidget{font-size:18px;font-bold;font-family: 微软雅黑;}");
  setLayout(v_layout_2);
}

//void MyGradeTableWidget::runHandleExcel()
//{

//  try {
//      int size = searchDate.size();

//      QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间

//      QString str = dateTime .toString("yyyy-MM-dd hh：mm：ss");//格式化时间

//      QString  strm = QApplication::applicationDirPath();
//      strm += "/导出数据";

//      QDir path; // 创建一个QDir变量
//      if (!path.exists(strm)) {  // 使用QDir成员函数exists()来判断文件夹是否存在
//          path.mkdir(strm);  // 使用mkdir来创建文件夹
//      }
//      strm +=  "/" + str + "的打靶数据导出.xlsx";
//      QByteArray strmData = strm.toUtf8();
//      char *strm_data = strmData.data();


//      //初始化
//      Py_Initialize();

//      //加载脚本
//      PyObject *pHandleExcel = PyImport_ImportModule("handleExcel");
//      //获取函数名
//      PyObject *pFunc_Name = PyObject_GetAttrString(pHandleExcel,"main");

//      PyObject* pArgsT = PyTuple_New(size+1);
//      //将要查询的靶号和分组赋值给元组
//      PyObject *info = PyDict_New();

//      PyDict_SetItemString(info,"check_addr",Py_BuildValue("i",baHao));
//      PyDict_SetItemString(info,"check_group",Py_BuildValue("i",fenZu));
//      PyDict_SetItemString(info,"path",Py_BuildValue("s",strm_data));
//      PyTuple_SetItem(pArgsT,0,info);

//      //判断函数是否可用
//      if(pHandleExcel && PyCallable_Check(pFunc_Name))
//      {
//          for(int i=0;i<size;i++){
//              PyObject* pArgsD = PyDict_New();

//              QByteArray strName = searchDate[i].user_name.toUtf8();
//              char *Name = strName.data();
//              PyDict_SetItemString(pArgsD,"user_name",Py_BuildValue("s",Name));
//              PyDict_SetItemString(pArgsD,"addr",Py_BuildValue("i",searchDate[i].addr));
//              PyDict_SetItemString(pArgsD,"groupnumber",Py_BuildValue("i",searchDate[i].group_number));
//              PyDict_SetItemString(pArgsD,"cn",Py_BuildValue("i",searchDate[i].cylinder_number));
//              //将字典赋值给元组
//              PyTuple_SetItem(pArgsT,i+1,pArgsD);
//          }

//          PyObject_CallObject(pFunc_Name,pArgsT);
//      }
//      //销毁
//      Py_Finalize();
//  } catch (std::exception &ex) {
//      MYLOG<<ex.what();
//      qWarning()<<"MyGradeTableWidget-exception"<<ex.what();
//      return ;
//  }

//}

//void MyGradeTableWidget::changeAddrandGroupnumber(int addr, int groupnumber)
//{
//  initconfig.setIntValue("searchDate","searchDateAddr",addr);
//  initconfig.setIntValue("searchDate","searchDateGroupNumber",groupnumber);

//}

//void MyGradeTableWidget::changeDate(QString time)
//{
//  initconfig.setStringValue("searchDate","searchDateDate",time);
//}

//导出excel成绩表
void MyGradeTableWidget::out_clicked()
{
  try{
      QProcess process(this);

      if(process.startDetached("./handleexcel.exe"))
          qDebug()<<"**************handleExcel进程启动******************";
      else
          QMessageBox::information(this,tr("提示"),tr("导出失败!"),QMessageBox::Ok);
      process.close();

      if(process.state() == QProcess::NotRunning)
          qDebug()<<"**************handleExcel进程关闭******************";

  }
  catch(std::exception &ex)
  {
    MYLOG<<ex.what();
    qWarning()<<"MyGradeTableWidget-exception"<<ex.what();
    return ;
  }
}

void MyGradeTableWidget::dateChange(const QDate &date)
{
  QDate m_date = date;
  currentDate = m_date.toString("yyyy-MM-dd");
  //发送改变日期信号
  emit signalDateChange(currentDate);
}

void MyGradeTableWidget::check_clicked()
{
  fenZu = lineEditGroup->text().toInt();
  baHao = lineEditNum->text().toInt();

//  searchData = {};

//  searchData = sqliteTools->searchGradeTable(fenZu,baHao,currentDate);

  //触发信号发送获取查询信息标志
  emit signalSearchdate(fenZu,baHao,currentDate);
  //触发发送改变的靶号和组号
  emit signal_addr_groupnumber_change(baHao,fenZu);

//  updateGrade(searchDate);

}

void MyGradeTableWidget::updateGrade(QVector<Target_Info_Table>& data)
{
  try{
    int msgSize = data.size();

    tableWidget->setRowCount(0);

    for(int i = 0;i < BulletNumber;i++)
      {
        tableWidget->insertRow(i);
      }

    if(baHao != 0 && fenZu != 0)
      {
        QList<int> m_list;
        for(int i = 0;i < msgSize;i++)
          {
            m_list.append(data[i].cylinder_number);
          }

        baWei = new QTableWidgetItem(QString::number(baHao));
        tableWidget->setItem(0,0,baWei);
//        xlsx.write(2,1,QString::number(baHao));
        fenZuIndex = new QTableWidgetItem(QString::number(fenZu));
        tableWidget->setItem(0,1,fenZuIndex);
//        xlsx.write(2,2,QString::number(fenZu));
        if(msgSize > 0)
          {
            name = new QTableWidgetItem(data[0].user_name);
            tableWidget->setItem(0,2,name);
//            xlsx.write(2 ,3,data[0].user_name);
          }
        int sum = 0,i;
        for(i = 0;i < m_list.size() && i < BulletNumber;i++)
          {
            sum += m_list[i];
            onlyHuanShu = new QTableWidgetItem(QString::number(m_list[i]));
            tableWidget->setItem(0,i + 3,onlyHuanShu);
//            xlsx.write(2 ,i + 4,QString::number(m_list[i]));
          }
        allSum = new QTableWidgetItem(QString::number(sum));
        tableWidget->setItem(0,33,allSum);
//        xlsx.write(2 ,34,QString::number(sum));
      }else if(baHao != 0 && fenZu == 0)
      {
        QVector<int> groupVec;
        QVector<QString> nameVec;

        for(int i = 0;i < msgSize;i++)
          {
            groupVec.append(data[i].group_number);
            nameVec.append(data[i].user_name);
          }

        for(int i=0;i<groupVec.size();i++){
            for(int j=i+1;j<groupVec.size();j++){
                if(groupVec[j]==groupVec[i]){
                    groupVec.remove(j);
                    j--;
                  }
              }
          }

        for(int i=0;i<nameVec.size();i++){
            for(int j=i+1;j<nameVec.size();j++){
                if(nameVec[j]==nameVec[i]){
                    nameVec.remove(j);
                    j--;
                  }
              }
          }

        for(int i = 0;i < groupVec.size();i++)
          {
            QList<int> m_list;
            for(int s = 0;s < msgSize;s++)
              {
                if(groupVec[i] == data[s].group_number)
                  {
                    m_list.append(data[i].cylinder_number);
                  }
              }
            baWei = new QTableWidgetItem(QString::number(baHao));
            tableWidget->setItem(i,0,baWei);
//            xlsx.write(i + 2,1,QString::number(baHao));

            fenZuIndex = new QTableWidgetItem(QString::number(groupVec[i]));
            tableWidget->setItem(i,1,fenZuIndex);
//            xlsx.write(i+2,2,QString::number(groupVec[i]));
            if(nameVec.size() > i)
              {
                name = new QTableWidgetItem(nameVec[i]);
                tableWidget->setItem(i,2,name);
//                xlsx.write(i+2 ,3,nameVec[i]);
              }else{
                name = new QTableWidgetItem("root");
                tableWidget->setItem(i,2,name);
//                xlsx.write(i+2 ,3,"root");
              }

            int sum = 0;
            for(int j = 0;j < m_list.size() && j < BulletNumber;j++)
              {
                sum += m_list[j];
                onlyHuanShu = new QTableWidgetItem(QString::number(m_list[j]));
                tableWidget->setItem(i,j + 3,onlyHuanShu);
//                xlsx.write(2 + i ,j+4,QString::number(m_list[j]));
              }
            allSum = new QTableWidgetItem(QString::number(sum));
            tableWidget->setItem(i,33,allSum);
//            xlsx.write(2 + i ,34,QString::number(sum));
          }
      }
    else if(fenZu != 0 && baHao == 0)
      {
        QVector<int> numVec;
        QVector<QString> nameVec;
        for(int i = 0;i < msgSize;i++)
          {
            numVec.append(data[i].addr);
            nameVec.append(data[i].user_name);
          }

        for(int i=0;i<numVec.size();i++){
            for(int j=i+1;j<numVec.size();j++){
                if(numVec[j]==numVec[i]){
                    numVec.remove(j);
                    j--;
                  }
              }
          }
        for(int i=0;i<nameVec.size();i++){
            for(int j=i+1;j<nameVec.size();j++){
                if(nameVec[j]==nameVec[i]){
                    nameVec.remove(j);
                    j--;
                  }
              }
          }
        for(int i = 0;i < numVec.size();i++)
          {
            QList<int> m_list;
            for(int s = 0;s < msgSize;s++)
              {
                if(numVec[i] == data[s].addr)
                  {
                    m_list.append(data[s].cylinder_number);
                  }
              }
            baWei = new QTableWidgetItem(QString::number(numVec[i]));
            tableWidget->setItem(i,0,baWei);
//            xlsx.write(i + 2,1,QString::number(numVec[i]));

            fenZuIndex = new QTableWidgetItem(QString::number(fenZu));
            tableWidget->setItem(i,1,fenZuIndex);
//            xlsx.write(i+2,2,QString::number(fenZu));

            if(nameVec.size() > i)
              {
                name = new QTableWidgetItem(nameVec[i]);
                tableWidget->setItem(i,2,name);
//                xlsx.write(i+2 ,3,nameVec[i]);
              }else{
                name = new QTableWidgetItem("root");
                tableWidget->setItem(i,2,name);
//                xlsx.write(i+2 ,3,"root");
              }
            int sum = 0;
            for(int j = 0;j < m_list.size() && j < BulletNumber;j++)
              {
                sum += m_list[j];
                onlyHuanShu = new QTableWidgetItem(QString::number(m_list[j]));
                tableWidget->setItem(i,j + 3,onlyHuanShu);
//                xlsx.write(2 + i ,j+4,QString::number(m_list[j]));
              }
            allSum = new QTableWidgetItem(QString::number(sum));
            tableWidget->setItem(i,33,allSum);
//            xlsx.write(2 + i ,34,QString::number(sum));
          }
      }
  }
  catch(std::exception &ex)
  {
    MYLOG<<ex.what();
    qWarning()<<"MyGradeTableWidget-updateGrade"<<ex.what();
    return ;
  }
}
